package com.usiful.utils;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

/**
 * properties文件工具类
 * @author [周织能]
 *
 */
public class PropertiesUtil {
	
	private static PropertiesUtil mInstance;
	protected Properties props;
	// 属性文件的路径
	protected String confFileName;
	
	private PropertiesUtil(String confFile) {
		confFileName = confFile;
		props = new Properties();
		InputStream in;
		try {
			in = new BufferedInputStream(new FileInputStream(confFileName));
			props.load(in);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public static PropertiesUtil getInstance(String file) {
		if(mInstance == null) {
			mInstance = new PropertiesUtil(file);
		}
		return mInstance;
	}
	
	/**
	 * 读取属性文件中相应键的值
	 * 
	 * @param key
	 *            主键
	 * @return String
	 */
	public String get(String key) {
		return props.getProperty(key);
	}

	/**
	 * 根据主键key读取主键的值value
	 * 
	 * @param filePath
	 *            属性文件路径
	 * @param key
	 *            键名
	 */
	public static String readValue(String filePath, String key) {
		Properties props = new Properties();
		try {
			InputStream in = new BufferedInputStream(new FileInputStream(filePath));
			props.load(in);
			String value = props.getProperty(key);
			System.out.println(key + "键的值是：" + value);
			return value;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 更新（或插入）一对properties信息(主键及其键值) 如果该主键已经存在，更新该主键的值； 如果该主键不存在，则插件一对键值。
	 * 
	 * @param keyname
	 *            键名
	 * @param keyvalue
	 *            键值
	 */
	public void set(String key, String value) {
		try {
			OutputStream fos = new FileOutputStream(confFileName);
			props.setProperty(key, value);
			props.store(fos, "Update '" + key + "' value");
		} catch (IOException e) {
			System.err.println("属性文件更新错误");
		}
	}

	/**
	 * 更新properties文件的键值对 如果该主键已经存在，更新该主键的值； 如果该主键不存在，则插件一对键值。
	 * 
	 * @param keyname
	 *            键名
	 * @param keyvalue
	 *            键值
	 */
	public void update(String key, String value) {
		try {
			props.load(new FileInputStream(confFileName));
			OutputStream fos = new FileOutputStream(confFileName);
			props.setProperty(key,value);
			props.store(fos, "Update '" + key + "' value");
		} catch (IOException e) {
			System.err.println("属性文件更新错误");
		}
	}
}
